
from django.shortcuts import render

# Create your views here.

from rest_framework import viewsets
from rest_framework import mixins
from rest_framework.permissions import IsAuthenticated  # 是否登录权限
# 是否是当前用户操作收藏，
from rest_framework_jwt.authentication import JSONWebTokenAuthentication  # 前端与后端使用jwt
from rest_framework.authentication import SessionAuthentication  # 后端登录api调试时用了SessionAuthentication

from .models import UserFav, UserLeavingMessage,UserAddress
from .serializers import UserFavSerializer, UserFavDetailSerializer, LeavingMessageSerializers, AddressSerializer
from utils.permissions import IsOwnerOrReadOnly  # 收藏取消时权限，验证是否是当前用户


class UserFavViewSet(mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.DestroyModelMixin,
                     mixins.ListModelMixin, viewsets.GenericViewSet):
    """
    list:
        获取用户收藏列表
    retrieve:
        判断某个商品身份已经收藏
    create:
        收藏商品
    """
    # queryset = UserFav.objects.all() # 重写了get_queryset()方法，就不要这里了
    permission_classes = (IsAuthenticated,)  # 权限,用户未登录访问用户收藏时，返回401
    authentication_classes = [JSONWebTokenAuthentication, SessionAuthentication]  # 配置jwt和Session两种模式
    lookup_field = "goods_id"  # 默认根据id来查找，lookup_field自定义字段来查找,这里设置goods_id外键字段来查找

    def get_queryset(self):
        """重写该方法，获取当前用户queryset对象"""
        return UserFav.objects.filter(user=self.request.user)

    # 方法1：重写mixins.CreateModelMixin中perform_create()方法来实现收藏功能
    # 方法2 使用信号量来实现
    # def perform_create(self, serializer):
    #     instance = serializer.save()
    #     goods = instance.goods
    #     goods.fav_num += 1
    #     goods.save()

    def get_serializer_class(self):
        if self.action == "list":
            return UserFavDetailSerializer
        elif self.action == "create":
            return UserFavSerializer
        return UserFavSerializer


class LeavingMessageViewSet(mixins.ListModelMixin, mixins.CreateModelMixin, mixins.DestroyModelMixin,
                            viewsets.GenericViewSet):
    """
    list:
        获取用户留言
    create:
        添加留言
    delete:
        删除留言功能
    """
    permission_classes = (IsAuthenticated,)  # 权限,用户未登录访问用户收藏时，返回401
    authentication_classes = [JSONWebTokenAuthentication, SessionAuthentication]  # 配置jwt和Session两种模式
    serializer_class = LeavingMessageSerializers

    def get_queryset(self):
        return UserLeavingMessage.objects.filter(user=self.request.user)


class AddressViewSet(viewsets.ModelViewSet):  # viewsets.ModelViewSet增、删、改、查都做了
    """
    收货地址管理
    list:
        获取收货地址
    create:
        添加收货地址
    update:
        更新收货地址
    delete:
        删除收货地址
    """
    permission_classes = (IsAuthenticated, IsOwnerOrReadOnly)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    serializer_class = AddressSerializer

    def get_queryset(self):
        return UserAddress.objects.filter(user=self.request.user)